package com.cll.pmis.controller;

import com.cll.pmis.common.Constants;
import com.cll.pmis.common.Result;
import com.cll.pmis.common.security.BCryptPasswordUtil;
import com.cll.pmis.common.security.SysUser;
import com.cll.pmis.common.validator.ValidatorUtils;
import com.cll.pmis.common.validator.group.Insert;
import com.cll.pmis.common.vcode.Captcha;
import com.cll.pmis.common.vcode.GifCaptcha;
import com.cll.pmis.entity.User;
import com.cll.pmis.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 权限控制器
 *
 * @author chenliangliang
 * @date 2018/6/23
 */
@Slf4j
@Controller
@RequestMapping("/auth")
public class AuthController {

    private IUserService userService;

    protected AuthController(IUserService userService){
        this.userService=userService;
    }


    @RequestMapping("/error")
    @ResponseBody
    public Result error( @RequestAttribute("error") String error){
        //model.addAttribute("msg",error);
        return Result.fail(error);
    }

    @PostMapping("/login")
    @ResponseBody
    public Result login(HttpServletRequest request, @RequestBody User user
                        /*@RequestParam("captcha") String captcha*/){

        ValidatorUtils.validateEntity(user,Insert.class);
//        //对验证码进行验证
//        if (StringUtils.isEmpty(captcha)) {
//            return Result.fail("验证码不存在！");
//        }
//        String codeExpired = (String) session.getAttribute("v_code");
//        if (codeExpired == null) {
//            return Result.fail("验证码不存在！");
//        }
//
//        String[] str = StringUtils.split(codeExpired, "#");
//        String vcode = str[0];
//        if (!StringUtils.equalsIgnoreCase(vcode, captcha)) {
//            log.error("验证码错误");
//            return Result.fail("验证码错误");
//        }
//        long expired = Long.parseLong(str[1]);
//        if (expired < System.currentTimeMillis()) {
//            log.error("验证码已过期");
//            return Result.fail("验证码已过期");
//        }
//
//        session.removeAttribute("v_code");

        SysUser user1 = userService.login(user.getUsername(), user.getPassword());

        request.getSession().setAttribute("user",user1);
        System.out.println(user1);
        System.out.println("login: "+request.getSession().getId());
        return Result.ok(user1);
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public Result logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.ok("");
    }


    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        try {
            System.out.println();
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");
            //response.setContentType("image/jpeg");


            /**
             * gif格式动画验证码
             * 宽，高，位数。
             */
            Captcha captcha = new GifCaptcha(146, 33, 4);
            //输出
            captcha.out(response.getOutputStream());
            //存入Session
            long expired = System.currentTimeMillis() + 60000;
            //session.removeAttribute("v_code");
            request.getSession(true).setAttribute("v_code", captcha.text() + "#" + expired);
            //System.out.println(captcha.text() + "#" + expired);
        } catch (Exception e) {
            log.error("获取验证码异常",e);
        }
    }


    @PostMapping("/register")
    @ResponseBody
    public Result register( @RequestParam("username") String username, @RequestParam("password") String password){

        if (StringUtils.isAnyEmpty(username,password)){
            return Result.fail(Constants.PARAM_ERROR);
        }
        User user=new User();
        user.setUsername(username);
        user.setPassword(BCryptPasswordUtil.encode(password));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        try {
            if (userService.insert(user)){
                return Result.ok(user);
            }else {
                return Result.fail("注册失败");
            }
        }catch (Exception e){
            log.warn("用户注册异常:{}",e.getMessage());
            return Result.fail("用户名已存在");
        }

    }
}
